<template>
	<view class="container">
		<view class="status_bar"></view>
		<!-- <view class="head flex-row">
			<view class="title">登录</view>
		</view> -->
		<view class="logo-wrap">
			<image src="../static/image/logo.png" mode=""></image>
		</view>
		<view class="input-wrap">
			<!-- <u--input class="input" v-model="form.telephone" type="text" placeholder="手机号" border="none"
				placeholderStyle="color:#9d9ea0"></u--input> -->
			<u--input class="input" placeholder="请输入账号/靓号" prefixIcon="account"
				prefixIconStyle="font-size: 26px;color: #909399" v-model="form.loginName" type="text" border="none"
				placeholderStyle="color:#9d9ea0"></u--input>
		</view>

		<view class="input-wrap1">
			<u--input class="input" placeholder="请输入密码" prefixIcon="lock"
				prefixIconStyle="font-size: 26px;color: #909399" v-model="form.loginPsw" :password="passwordShow"
				border="none" placeholderStyle="color:#9d9ea0"></u--input>
			<image v-if="eyeShow==true" src="../static/image/icon-eye@3x.png" class="eye" @tap="oneye()">
			</image>

			<image v-else src="../static/image/icon-eye-o@3x.png" class="eye-o" @tap="oneyeOpen()"></image>

		</view>
		<view class="wangji" @tap="handleRegister(1)">忘记密码</view>
		<view class="login" :class="{able: isAbled}" :type="agree ? 'primary' : 'default'" @tap="login">登录</view>
		<view style="font-size: 12px;text-align: center;margin-top: 20px;display: flex;justify-content: center;">
			<span>
				<u-checkbox-group v-model="agree">
					<u-checkbox class="checkbox"></u-checkbox>
				</u-checkbox-group>
			</span>
			已阅读并同意<span style="color: blue;" @tap="gopage1()">应用程序协议</span>和<span style="color: blue;"
				@tap="gopage()">信息保护政策</span>
		</view>
		<view class="register-btn" @tap="handleRegister(2)">新用户注册</view>


		<!-- <view class="tip">
			<view class="item">客户端为DEMO(非商业用途)，如有侵权，请及时联系我们</view>
			<view class="item">反馈地址：<text class="link" @tap="toPage('/pages/web')">点击访问</text></view>
		</view> -->
	</view>
</template>

<script>
	let EventType = require("./index/utils/event-type.js");
	let EventBus = require("./index/utils/event-bus.js");
	let ToolKits = require("./index/utils/toolkits.js");
	let imManager = require("./index/utils/im-manager.js");
	export default {
		data() {
			return {
				agree: [], // 使用数组存储选中的值（u-checkbox-group 默认格式）
				form: {
					loginPsw: '',
					loginName: '',
					clientVersion: '',
					telephone: '',
					password: '',
				},
				eyeShow: true,
				passwordShow: true,
			}
		},
		computed: {
			isAbled() {
				return !this.$validate.isNull(this.form.telephone) && !this.$validate.isNull(this.form.password)
			}
		},
		onLoad(option) {
			let data = option;
			let key = Object.keys(data)[0];
			console.log('键名:', key);
			// 提取 JSON 部分
			let jsonMatch = key.match(/\[({.*})\]/);
			if (jsonMatch && jsonMatch[1]) {
				let jsonString = jsonMatch[1];
				let parsedObject = JSON.parse(jsonString); // 解析为对象
				console.log('解析后的对象:', parsedObject);
				// 输出: { acc: "400093", pas: "123456", name: "浮沉若梦" }
				if (parsedObject != '') {
					this.form.loginName = parsedObject.acc
					this.form.loginPsw = parsedObject.pas
				}

			}
			if (parsedObject != '') {
				this.form.loginName = parsedObject.acc
				this.form.loginPsw = parsedObject.pas
			}

		},
		onBackPress() {
			// 阻止返回操作
			return true;
		},

		onShow() {
			// uni.clearStorageSync()
		},
		methods: {
			onRegister() {
				// 注册按钮点击逻辑
				console.log('注册按钮被点击');
				uni.showToast({
					title: '注册成功！',
					icon: 'success',
				});
			},
			gopage() {
				this.toPage('/pages/mine/settings/message/message');
			},
			gopage1() {
				this.toPage('/pages/mine/settings/message/message1');
			},
			handleRegister(id) {
				// alert(111)
				uni.navigateTo({
					url: `/pages/register?id=${id}` // 使用模板字符串将 id 作为参数附加到 URL
				});
			},
			oneye() {
				this.passwordShow = false
				this.eyeShow = false
			},
			oneyeOpen() {
				this.passwordShow = true
				this.eyeShow = true
			},
			login() {
				// 数据校验 
				if (this.form.loginName == "") {
					return this.$util.toast('昵称不能为空')
				}
				if (this.form.loginPsw == "") {
					return this.$util.toast('登录密码')
				}
				if (this.agree.length === 0) {
					uni.showToast({
						title: '请先同意协议',
						icon: 'none',
						duration: 2000,
					});
					return;
				}
				uni.showLoading()
				const newDataObj = {
					"loginName": this.form.loginName,
					"loginPsw": this.form.loginPsw,
					"clientVersion": "2",
					"deviceInfo": "1",
					"osType": "1"
				};
				const newDataJsonStr = JSON.stringify(newDataObj)
				const requestData = {
					"processorId": '1009',
					"newData": newDataJsonStr
				};


				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					// http://chat.zwsmcn.com:8090/rest_post
					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						const updateInfoStr = JSON.stringify(res.data.returnValue);
						const updateInfoObj = JSON.parse(updateInfoStr);
						console.log("版本更新信息:", updateInfoObj);
						try {
							const parsedObj = JSON.parse(updateInfoObj);
							const updateInfo = JSON.parse(parsedObj.update_info);
							const authedInfo = JSON.parse(parsedObj.authed_info);

							console.log(updateInfo);
							console.log(authedInfo);

							var loginInfo = {
								loginUserId: authedInfo.user_uid,
								loginToken: this.form.loginPsw
							};


							uni.setStorageSync('loginInfo', loginInfo)
							console.log(this.form);
							console.log(loginInfo);
							console.log(imManager.IM_SERVER_URL);
							uni.IMSDK.loginImpl(loginInfo, imManager.IM_SERVER_URL, false);
							console.log("版本更新信息:", updateInfo);
							console.log("用户授权信息:", authedInfo);
							let user_uid = authedInfo.user_uid

							let token = authedInfo.token
							console.log()
							uni.setStorageSync('user_uid', user_uid)
							uni.setStorageSync('userId', user_uid)
							uni.setStorageSync('token', token)


							uni.setStorageSync('user_uid', authedInfo.user_uid)
							uni.setStorageSync('userId', authedInfo.user_uid)
							uni.setStorageSync('nickname', authedInfo.nickname)
							uni.setStorageSync('user_avatar_file_name', authedInfo.userAvatarFileName)
							uni.setStorageSync('user_level', authedInfo.user_level)

							// #ifdef APP


							this.DB.isTable("friend" + uni.getStorageSync("user_uid")).then((res) => {
								// console.log(res);
								if (!res) {
									let sql =
										'id INTEGER PRIMARY KEY AUTOINCREMENT, nickname text, userAvatarFileName text, user_mail text, user_sex text, user_uid text, online text,whatsUp text, online_time text,ex10 text,friendRemark text';
									this.DB.createTable("friend" + uni.getStorageSync("user_uid"), sql)
										.then(res_f => {
											console.log("创建friend表成功", res_f);
										})
										.catch(error => {
											console.log("创建表失败", error);
										});
								}
							})
							this.DB.isTable("chat" + uni.getStorageSync("user_uid")).then((res_c) => {

								console.log(res_c);
								if (!res_c) {
									let sql1 =
										'id INTEGER PRIMARY KEY AUTOINCREMENT, type text, dataContent text, from1 text, to1 text, QoS text, typeu text, sm text, fp text, retryCount text DEFAULT 0, time text,nickname text,avatar text,is_read text DEFAULT 0,gid text,is_collect text DEFAULT 0,del_flag text DEFAULT 0,chat_type text,relatedId text,is_top INTEGER DEFAULT 0,is_mute INTEGER DEFAULT 0';
									// console.log(sql1);
									DB.createTable("chat" + uni.getStorageSync("user_uid"),
											sql1)
										.then(res_cs => {
											console.log("创建chat表成功", res_cs);
										})
										.catch(error => {
											console.log("创建表失败", error);
										});
								}

							})

							// #endif


							console.log('0111111111111111111111111111111')
						

							// 缓存账号
							// 定义 loginInfo
							var loginInfohc = {
								acc: this.form.loginName,
								pas: this.form.loginPsw,
								name: authedInfo.nickname
							};
							// 从缓存中获取已存在的数组（如果不存在则初始化为空数组）
							var arr = uni.getStorageSync('loginInfoArr') || [];
							// 将新的 loginInfo 添加到数组中
							arr.push(loginInfohc);
							// 将数组存回缓存
							uni.setStorageSync('loginInfoArr', arr);
							console.log('存储成功:', arr);

							if (authedInfo != null) {
								console.log(112)
								uni.hideLoading();
								uni.switchTab({
									url: '/pages/mine/index'
								});
							} else {
								uni.hideLoading();
							}

						} catch (error) {
							uni.hideLoading();
							return this.$util.toast('登陆失败')
							console.error("解析JSON数据出错:", error);
						}

						// 输出类似这样的对象（格式示意）：
						// {
						//     latestClientAPKFileSize: 0,
						//     latestClientAPKURL: "http://chat.ylapp88.com//Chat4a.apk",
						//     latestClientAPKVercionCode: "432",
						//     needUpdate: true
						// }
						console.log(res.data.returnValue)
					},
					fail: res => {
						uni.hideLoading();
						console.log(res);
					}
				});
				// 数据校验
				if (!this.isAbled) return
				if (!this.$validate.isPhone(this.form.telephone)) {
					return this.$util.toast('手机号码格式错误')
				}
				if (this.$validate.isNull(this.form.password)) {
					return this.$util.toast('请输入登录密码')
				}

				return;
				// 跳转首页
				// this.toTab('/pages/message/index')
				uni.request({
					method: 'POST',
					url: this.$api.login,
					data: this.form,
					header: this.$util.getHeader(),
					success: res => {
						uni.hideLoading()
						if (res.data.code) {
							return this.$util.toast(res.data.msg)
						}

						// 缓存数据
						let {
							userId,
							userFace,
							userToken,
							token
						} = res.data.data
						uni.setStorageSync('userId', userId)
						uni.setStorageSync('userToken', userToken)
						uni.setStorageSync('userFace', userFace ? this.$api.staticPath + userFace : '')
						uni.setStorageSync('token', token)

						

						// 跳转首页
						// this.toTab('/pages/message/index')
					},
					fail: err => {
						uni.hideLoading()
						this.$util.toast('登录失败')
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #f0f0f0;
	}

	.tip {
		width: 100%;
		text-align: center;
		padding: 0 30upx;
		position: absolute;
		bottom: 30upx;

		.item {
			color: #777;
			font-size: 24upx;
			margin-top: 10upx;

			.link {
				color: blue;
				font-size: 24upx;
			}
		}
	}


	.wangji {
		// width: 80%;
		text-indent: 20%;
		height: 40px;
		line-height: 40px;
		display: inline-block;
		margin-left: 13%;
		width: 100px;
	}

	.login {
		color: #fff;
		// opacity: 0.6;
		margin: 70upx 100upx 0 100upx;
		padding: 20upx 0;
		text-align: center;
		border-radius: 10upx;
		background: #d54827;

		&.able {
			opacity: 1;
			background-color: #4CD964;
		}
	}

	.logo-wrap {
		margin-top: 30%;
		margin-left: 40%;

		image {
			width: 180upx;
			height: 180upx;
			border-radius: 50%;

		}
	}

	.input-wrap {
		margin-left: -60upx;
	}

	.input {
		height: 80upx;
		padding: 0 20upx;
		margin: 60upx 100upx 0;
		background: #fafbfd;
		border-radius: 12upx;
		//border: 2upx solid #999;
		margin-left: 160upx;
	}

	.register-btn {
		width: 100%;
		text-align: center;
		color: #104c8a;
		font-weight: 300;
		margin-top: 20upx;
	}

	.input-wrap1 {
		margin-left: -60upx;
		position: relative;

		image {
			margin-right: 10upx;
			width: 45upx;
			height: 32upx;
			position: absolute;
			top: 30%;
			right: 13%;
		}
	}
</style>